// pages/index2/index2.js
const app = getApp()
//打错的题目放到erroroption
let erroroption=[]
Page({
  data: {
    question:{
      type:Array,
      value:[]
    },
    shuju: [],
    curret: 1, //第几题
    nums: 100, //题库题目的总数量
    isSelect: false, 
    subject: null,
    scoreFen: 1, //定义每道单选题的分值
    percent: 0, //进度条数量计算
    userSelect: '', //用户选择的题目个数
    score: 0, //用户答对的题目数量
    curt: '', //如果用户有选择就更新进度条
    zongfen: -1, //用户的总分
    btndis: false, //最后一题checked停止
    totalerrow: 0 ,//用户答错题的个数
    suiji:'00',
    suiji1:"00",
    jifen:0,
    // 倒计时
    pingData: [
      {
      "number": "1",//只有作答一次
      "time": "3600000",//一小时答题
      // "time": "3600",
      }
      ],
  },
  back(){
    wx.navigateBack({
      delta: 0,
    })
  }, 
  onLoad: function (options) {
  // 倒计时
    var that = this
    that.setData({
    listData: that.data.pingData
    })
    that.setCountDown(); 
    that.setTimeCount();

    wx.removeStorageSync('daui')
    var that = this;
    wx.request({
      url: 'XXXXXXXX?page=1&rows=10', //题目接口
      data: {
        
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        that.setData({
          //shuju:JSON.stringify(res.data.data.rows)
          shuju: res.data.data.rows,
          // subject: res.data.data.rows[that.data.curret - 1],
          nums: res.data.data.rows.length,
        })
 
      }
    })
  },
  checkboxChange(e) {
    this.setData({
      userSelect: e.detail.value
    })
  },
  
  submit() {
    wx.setStorageSync('leng1', this.data.shuju.length)
    //1.获取用户选项，并判空
    let userSelect = this.data.userSelect;
    if (!userSelect || userSelect < 1) {
      wx.showToast({
        icon: 'none',
        title: '您还没有选择答案！',
      })
      return
    }
 
 //随机数答题
    var random = Math.floor(Math.random() * 10);
    this.setData({
      suiji: random
    })
  //  console.log("出现的随机数",this.data.suiji)
 
    //2.如果用户有选择就更新进度条
    let curt = this.data.curret; //2
    //进度条
    this.setData({
      percent: (curt / this.data.shuju.length * 100).toFixed(2),
    })
    //判断所选择的答案是否在正确答案中
    let daan = this.data.subject.answer_choices;
    let a = []
    daan.forEach(item => {
      a.push(item.content)
    })
    console.log("正确答案是：", a)
    let leng = daan.length;
    console.log("多选题选择了", userSelect)
    //选择答案的个数和长度
    let daan2 = userSelect;
    let leng2 = daan2.length;
    //3.判断用户是否答对
  if(a.sort().toString()==daan2.sort().toString()){
     let score = this.data.score+1;
    //  console.log("答对了：",score)
     this.setData({
      score:score
     })
  }else{
  //4.记录用户答错的题，帮用户查漏补缺
    let subjectNon  = this.data.subject;
     subjectNon.userSelect = userSelect;
     //将用户答错的题放到常量erroroption
     erroroption.push(subjectNon)
    //  console.log("错题",erroroption)
  }
   //判断是否答题结束4
    if(curt+1>this.data.shuju.length){
      //5.在用户答完最后一道题的时候对用户进行打分
      let userScore = this.data.score;
      let scoreFen = this.data.scoreFen;
      this.setData({
        zongfen:scoreFen*userScore,
        totalerrow:erroroption.length
      })
      wx.showToast({
        icon:'none',
        title: '已经是最后一题了！',
      })
      this.setData({
        btndis:true
      })
       //数据缓存
       wx.setStorageSync('errodat', erroroption)
 
       //数据读取
       let name = wx.getStorageSync('xingming');
       let stuNum = wx.getStorageSync('stuNum');
      let daui = wx.getStorageSync('daui');
      let chang = this.data.shuju.length;
     var that = this
      if(daui/chang*100>=80){
       let num = this.data.jifen
        let jifen = num+4
        console.log("加4分")
        console.log(jifen)
 
        that.setData({
          jifen:jifen
        })
      }else if(daui/chang*100>=60){
       let num = this.data.jifen
        console.log("加2分")
        let jifen = num+2
        console.log(jifen)
        that.setData({
          jifen:jifen
        })
      }else if(daui/chang*100<60){
       let num = this.data.jifen
        console.log("不加分")
        let jifen = num+1
        console.log(jifen)
        that.setData({
          jifen:jifen
        })
      }
       let integral = this.data.jifen;
       wx.setStorageSync('integral', integral)
       console.log(name)
       console.log(phone)
       console.log(integral)
       //向后端提交数据
       wx.request({
         url: 'url',
         header:{
           "Content-Type":"application/x-www-form-urlencoded"
         },
         method:"POST",
         data:{name:name,stuNum:stuNum,integral:integral},
         success:function(res){
            console.log(res.data)
            if (res.data.status == 0) {
              wx.showToast({
                title: '提交失败！！！',
                icon: 'loading',
                duration: 1500
              })
            }else{
              wx.showToast({
               title: '提交成功！！！',//这里打印出登录成功
                icon: 'success',
                duration: 1000
              })
            }
         },
         fail:function(){
 
         }
       })
      return
  }
  //  数据佳佳
  if (this.data.curret < this.data.shuju.length) {
    this.setData({
      userSelect:'',
      // subject: this.data.shuju[this.data.suiji],
      curret: ++this.data.curret,
      isSelect:false
    })
    console.log("题目：",this.data.subject)
    return
  }
  },
  //自定义弹框
  powerDrawer: function (e) {
    var currentStatu = e.currentTarget.dataset.statu;
    this.util(currentStatu)
   },
   util: function(currentStatu){
    /* 动画部分 */
    // 第1步：创建动画实例
    var animation = wx.createAnimation({
     duration: 200, //动画时长
     timingFunction: "linear", //线性
     delay: 0 //0则不延迟
    });  
    // 第2步：这个动画实例赋给当前的动画实例
    this.animation = animation;
    // 第3步：执行第一组动画
    animation.opacity(0).rotateX(-100).step();
    // 第4步：导出动画对象赋给数据对象储存
    this.setData({
     animationData: animation.export()
    })
    // 第5步：设置定时器到指定时候后，执行第二组动画
    setTimeout(function () {
     // 执行第二组动画
     animation.opacity(1).rotateX(0).step();
     // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象
     this.setData({
      animationData: animation
     })  
     //关闭
     if (currentStatu == "close") {
      this.setData(
       {
        showModalStatus: false
       }
      );
     }
    }.bind(this), 200)
    // 显示
    if (currentStatu == "open") {
     this.setData(
      {
       showModalStatus: true
      }
     );
    }
   },
   //查看成绩
   tiku(){
     wx.switchTab({
       url: '/pages/score/score',
     })
   },
   //6.查看错题
   cuoti(){
      //1.跳页之前存数据
    
      //2.用全局变量的，将数据传给全局
      //app.globalData.globalerror = erroroption;
       //如果页面有tabbar,跳转就要改成 wx.switchTab()跳转
       wx.navigateTo({   
         url: '/pages/score/score',   
       })
   },
   /**
  * 60s倒计时
  */
  setTimeCount:function(){
    let time=this.data.time
    time--;
    if (time <= 0) {
    time = 0;
    }
    
    this.setData({
    time:time
    })
    setTimeout(this.setTimeCount,1000);
    },
    /**
    * 倒计时
    */
    setCountDown: function () {
    let time = 1000;
    let { listData } = this.data;
    let list = listData.map((v, i) => {
    if (v.time <= 0) {
    v.time = 0;
    }
    let formatTime = this.getFormat(v.time);
    v.time -= time;
    v.countDown = `${formatTime.hh}:${formatTime.mm}:${formatTime.ss}`;
  
    // console.log(v.countDown);
    return v;
    })
    this.setData({
    listData: list
    });
    setTimeout(this.setCountDown, time);
    },
    /**
    * 格式化时间
    */
    getFormat: function (msec) {
    let ss = parseInt(msec / 1000);
    let ms = parseInt(msec % 1000);
    let mm = 0;
    let hh = 0;
    if (ss > 60) {
    mm = parseInt(ss / 60);
    ss = parseInt(ss % 60);
    if (mm > 60) {
    hh = parseInt(mm / 60);
    mm = parseInt(mm % 60);
    }
    }
    ss = ss > 9 ? ss : `0${ss}`;
    mm = mm > 9 ? mm : `0${mm}`;
    hh = hh > 9 ? hh : `0${hh}`;
    return { ss, mm, hh };
    },
    onShow(){
       // 刷新
      wx.startPullDownRefresh()
    }
})